<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\LoginRequest;
use App\Models\AdminUser;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function login(LoginRequest $request)
    {
        // 查询账户是否存在
        try {
            $user = AdminUser::query()->where('username', $request->username)->firstOrFail();
        } catch (ModelNotFoundException $exception) {
            return $this->notFound('账号不存在');
        }

        $credentials = $request->only('username', 'password');

        if (!$token = Auth::guard('admin')->attempt($credentials)) {
            return $this->unauthorized('账号或密码错误');
        }

        $data = [
            'token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => Auth::guard('admin')->factory()->getTTL() * 60,
            'user' => $user,
        ];

        return $this->success($data);
    }
}
